import { createRouter, createWebHistory, RouteRecordRaw, Router } from "vue-router";
// import routes from "./router.default";
import routes from "@/router/router.default"

/**
 * 自动适配识别路由
 */
const autoRouters = () => {
  // @ts-ignore 读取views/page下的所有vue文件,并将其转换为路由
  const pages = import.meta.glob("../views/page/**/*.vue");
  Object.entries(pages).map(([page, component]) => {
    const addr = page.replace("../views/page", "").split("/").filter(Boolean);
    const paths = addr.map((_, index) => `/${addr.slice(0, index + 1).join("/")}`);
    paths.forEach(path => {
      let name = path.slice(path.lastIndexOf("/") + 1).replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
      if (path.endsWith(".vue")) {
        name = name.split(".")[0];
        path = path.split(".")[0].toLowerCase();
      }
    //   console.log(!routes)
      // @ts-ignore 判断routes路由名称是否存在
      if (!routes.at(0).children.find((route: RouteRecordRaw) => route.name === name)) {
        // @ts-ignore
        routes.at(0).children.push({name: name, path: "/page" + path, redirect: "", component: component, children: []});
      }
    });
  });
  console.log(routes)
  return routes;
};

/**
 * 创建路由
 */
const router: Router = createRouter({
  history: createWebHistory(),
  routes: autoRouters(),
});

/**
 * 前置路由守卫
 */
router.beforeEach((to, from, next) => {
//   const isLogin = localStorage.getItem("user");
//   if (to.name !== "Login" && !isLogin) {
//     next({ name: "Login" });
//   } else {
//     next();
//   }
});

/**
 * 后置路由守卫
 */
router.afterEach((to) => {
  // @ts-ignore
//   const el = document.querySelector(".tarot-menu-" + to.name);
//   const activeEl = document.querySelector(".active");
//   activeEl?.classList.remove("active");
//   el?.classList.add("active");


});

export default router;
